package cn.bby.tools.utils;

import cn.bby.tools.dialog.FieldCompareDialog;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiType;
import com.intellij.psi.PsiTypes;
import com.intellij.psi.javadoc.PsiDocComment;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @description: FieldUtil
 * @author: ben
 * @date: 2025/10/15 14:29
 * @version: 1.0
 */
public class FieldUtil {

    private static final List<String> boolPreStrList = List.of("is", "has", "have");
    private static final List<String> collSufStrList = List.of("list", "List", "set", "s");


    public static String getComment(PsiField field) {
        PsiDocComment docComment = field.getDocComment();
        if (docComment != null) {
            return docComment.getText().replaceAll("[*/]",  "").trim();
        }
        return Arrays.stream(field.getText().split("\n"))
                .map(String::trim)
                .filter(l->l.startsWith("/"))
                .map(l->l.replaceAll("[*/]",  "").trim())
                .filter(l-> !l.isEmpty())
                .collect(Collectors.joining(" "));
    }

    public record FieldRecord(Set<String> fuzzyNames, String fieldName, String lowerName) {
    }

    public static List<FieldRecord> getFuzzyFields(Project project, List<PsiField> overFields) {
        return overFields.stream()
                .map(field -> {
                    String fieldName = field.getName();
                    String name = fieldName.toLowerCase(Locale.ROOT);
                    Set<String> fuzzyNames = new HashSet<>();
                    fuzzyNames.add(name);
                    PsiType type = field.getType();
                    if (PsiTypes.booleanType().isAssignableFrom(type)) {
                        for (String pre : boolPreStrList) {
                            if (name.startsWith(pre)) {
                                fuzzyNames.add(name.substring(pre.length()));
                                break;
                            }
                        }
                    } else if (ClassChooseUtil.isCollType(project, type)) {
                        for (String suf : collSufStrList) {
                            if (name.endsWith(suf)) {
                                int end = name.length() - suf.length();
                                if (end > 1) {
                                    fuzzyNames.add(name.substring(0, end));
                                    break;
                                }
                            }
                        }
                    }
                    return new FieldRecord(fuzzyNames, fieldName, name);
                }).toList();
    }
}
